package com.web;

import com.bean.User;
import com.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/book/register")
public class RegisterServlet extends HttpServlet {
    /**
     * doGet 请求到页面上
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/register/register.jsp").forward(req, resp);
    }

    /**
     * doPost 处理注册逻辑
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        // 获取 Session 中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        // 判断参数是否为空
        if (username.length() == 0 || password.length() == 0 || gender.length() == 0 || email.length() == 0 || code.length() == 0) {
            // 把信息存到 message 中处理
            req.setAttribute("message", "字段不能为空！请重新输入哦");
            // 页面转发
            req.getRequestDispatcher("/register/result.jsp").forward(req, resp);
            // 返回
            return;
        }

        try {
            // 创建对象并实现方法
            new UserDao().insert(new User(username, password, gender, email));

            // 把信息存到 message 中处理
            req.setAttribute("message", "注册成功");
            // 页面转发
            req.getRequestDispatcher("/register/message.jsp").forward(req, resp);
        } catch (Exception e) {
            // 把异常信息打印到控制台
            e.printStackTrace();
            // 把信息存到 message 中处理
            req.setAttribute("message", e.getLocalizedMessage());
            // 页面转发
            req.getRequestDispatcher("/register/result.jsp").forward(req, resp);
        }
    }
}
